package com.xiaxueqi.web.home;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.niagara.context.SecurityContext;
import com.niagara.dao.Page;
import com.niagara.security.auth.entity.UserDetail;
import com.niagara.service.base.BaseService;
import com.niagara.web.struts2.CRUDActionSupport;
import com.niagara.web.struts2.Struts2Utils;
import com.xiaxueqi.entity.book.BookSelled;
import com.xiaxueqi.entity.book.BookStore;
import com.xiaxueqi.entity.security.AppUser;

@Results( { @Result(name = CRUDActionSupport.RELOAD, location = "selled-log.action", type = "redirect") })
public class SelledLogAction extends CRUDActionSupport<BookSelled> {
	private static final long serialVersionUID = 1L;

	@Autowired
	private BaseService baseService;
	private BookSelled entity;
	private Integer id;
	private Page<BookSelled> page;

	private UserDetail detail = SecurityContext.getUserDetail();
	private Integer userId = detail != null ? Integer.valueOf(detail
			.getUserId().intValue()) : null;

	private List<String> bookName = new ArrayList<String>();
	private List<String> buyerName = new ArrayList<String>();

	public List<String> getBookName() {
		return bookName;
	}

	public List<String> getBuyerName() {
		return buyerName;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Page<BookSelled> getPage() {
		return page;
	}
	// 销售记录的逻辑删除
	@Override
	public String delete() throws Exception {
		this.entity = this.baseService.get(BookSelled.class, this.id);
		this.entity.setDeleted("Y");
		this.baseService.update(this.entity);
		return RELOAD;
	}

	// 管理自己的销售列表
	@SuppressWarnings("unchecked")
	@Override
	public String list() throws Exception {
		Map map = Struts2Utils.getParameters();
		Integer pageNo = Struts2Utils.getIntParameter(PARAMS_PAGENO, Integer
				.valueOf(1));
		map.put("salerId", userId);
		this.page = this.baseService.findForPaging(BookSelled.class, map,
				pageNo, DEFAULT_PAGE_SIZE);
		List<BookSelled> bookSelled = this.page != null ? this.page
				.getPageList() : new ArrayList<BookSelled>();
		for (int i = 0; i < bookSelled.size(); i++) {
			this.bookName.add(this.baseService.get(BookStore.class,
					bookSelled.get(i).getBookId()).getBookName());
			this.buyerName.add(this.baseService.get(AppUser.class,
					bookSelled.get(i).getBuyerId()).getLoginId());
		}
		return SUCCESS;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (this.id != null) {
			this.entity = this.baseService.get(BookSelled.class, this.id);
		} else {
			this.entity = new BookSelled();
		}
	}

	@Override
	public String save() throws Exception {
		return RELOAD;
	}

	public BookSelled getModel() {
		return this.entity;
	}
}
